<?php

namespace humhub\modules\api\cccstream;

use Yii;
use humhub\modules\content\models\Content;

/**
 * 改造自 ContentContainerStream 用于课程目录获取，限制非成员用户获取
 */
class ContentContainerStream4 extends Stream
{

    public $contentContainer;

    public function init()
    {
        $_GET['from']  = '';
        $_GET['limit'] = 1000;
        $this->limit= 1000;
        parent::init();

        // Get Content Container by Param
        // 校验是否为成员
        if ($this->contentContainer->wall_id != "" && $this->contentContainer->isMember() ) {
            $this->activeQuery->andWhere("wall_entry.wall_id = " . $this->contentContainer->wall_id);

            //ID wallEntryId
            if( $wallEntryId = Yii::$app->getRequest()->get('id_wallentryId', 0) ){
                //上面默认筛选此Space/User(wall_id=*)里的所有内容
                //加上限定条件
                $this->activeQuery->andWhere("wall_entry.id = " . $wallEntryId);
            }

        } else {
            //Yii::warning("No wall id for content container " . get_class($this->contentContainer) . " - " . $this->contentContainer->getPrimaryKey() . " set - stopped stream action!");
            //// Block further execution
            //$this->activeQuery->andWhere("1=2");

            //不是成员也可以获取到
            $this->activeQuery->andWhere("wall_entry.wall_id = " . $this->contentContainer->wall_id);

            //ID wallEntryId
            if( $wallEntryId = Yii::$app->getRequest()->get('id_wallentryId', 0) ){
                //上面默认筛选此Space/User(wall_id=*)里的所有内容
                //加上限定条件
                $this->activeQuery->andWhere("wall_entry.id = " . $wallEntryId);
            }
        }

        /**
         * Limit to public posts when no member
         */
        if (!$this->contentContainer->canAccessPrivateContent($this->user)) {
            if(!Yii::$app->user->isGuest) {
                $this->activeQuery->andWhere("content.visibility=" . Content::VISIBILITY_PUBLIC . " OR content.created_by = :userId", [':userId' => $this->user->id]);
            } else {
                $this->activeQuery->andWhere("content.visibility=" . Content::VISIBILITY_PUBLIC);
            }
        }

        /**
         * Handle sticked posts only in content containers
         */
        if ($this->limit != 1) {
            if ($this->from == '') {
                $oldOrder = $this->activeQuery->orderBy;
                $this->activeQuery->orderBy("");

                $this->activeQuery->addOrderBy('content.created_at');
                $this->activeQuery->addOrderBy($oldOrder);
            } else {
                $this->activeQuery->andWhere("(content.sticked != 1 OR content.sticked is NULL)");
            }
        }
    }

    public function run_old()
    {
        return false;
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $wallEntries = $this->getWallEntries();

        $generatedWallEntryIds = [];
        $lastEntryId = "";
        $wallList = Array();
        $wallOne = Array();
        foreach ($wallEntries as $wallEntry) {

            $underlyingObject = $wallEntry->content->getPolymorphicRelation();

            if ($underlyingObject === null) {
                throw new Exception('内容获取失败.');
            }

            $underlyingObject->populateRelation('content', $wallEntry->content);

            //Public Provate \humhub\modules\content\widgets\WallEntryLabels::widget(['object' => $object]);
            if ($underlyingObject->content->isSticked()){
                $o['label'] = 'Sticked';
            }
            if ($underlyingObject->content->isArchived()){
                $o['label'] = 'Archived';
            }
            if ($underlyingObject->content->isPublic()){
                $o['label'] = 'Public';
            }

            //content
            if (!$underlyingObject instanceof \humhub\modules\post\models\Post){
                $o['contentname'] = $underlyingObject->getContentName();
            }
            $o['id'] = $underlyingObject->id;
            //$o['message'] = $underlyingObject->getWallOut();
            //$o['message'] = $underlyingObject->message;
            $o['message'] = \humhub\widgets\RichText::widget(['text' => $underlyingObject->message, 'record' => $underlyingObject]);
            $o['p_title'] = \humhub\widgets\RichText::widget(['text' => $underlyingObject->p_title, 'record' => $underlyingObject]);
            $o['created_at'] = $underlyingObject->created_at;
            $o['updated_at'] = $underlyingObject->updated_at;

            //Episode
            //$episode = \humhub\modules\api\models\CourseEpisode::find(['space_id' => $this->contentContainer->id]);
            //$episodes = \humhub\modules\api\models\CourseEpisode::findAll(['season_id' => $underlyingObject->id]);
            $o['episodes'] = [];
            //foreach($episodes AS $episode){
            //    $e['title']   = $episode['title'];
            //    $e['message'] = $episode['message'];
            //    $e['secs']    = $episode['secs'];
            //    $img = '';
            //    $file = \humhub\modules\file\models\File::findOne(['guid' => $episode['imgguid']]);
            //    if( $file ){
            //        if ($file->getMimeBaseType() == "image"){
            //            //$img = $file->getPreviewImageUrl(200, 200);
            //            $img = $file->getUrl();
            //        }
            //    }
            //    $e['image'] = $img;

            //    //Files
            //    //$files = \humhub\modules\file\models\File::findAll(array(
            //    //    'object_id' => $episode->id,
            //    //    'object_model' => \humhub\modules\api\models\CourseEpisode::className()
            //    //));
            //    //$e['files'] = [];
            //    //foreach ($files as $file){
            //    //    $f['url'] = $file->getUrl();
            //    //    $e['files'][] = $f;
            //    //}
            //    $e['video']   = $episode['video'];

            //    $o['episodes'][] = $e;
            //}

            //$wallOne['entry']  = $wallEntry; //table:wall_entry
            $wallOne['object'] = $o;
            $wallList[] = $wallOne;

            $generatedWallEntryIds[] = $wallEntry->id;
            $lastEntryId = $wallEntry->id;
        }
        return [
            'output' => $wallList,
        ];
    }

    public function run()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $wallEntries = $this->getWallEntries();

        $generatedWallEntryIds = [];
        $lastEntryId = "";
        $wallList = Array();
        $wallOne = Array();
        //foreach ($wallEntries as $wallEntry) {
            //Episode
            $o['episodes'] = [];
            foreach ($wallEntries as $wallEntry) {
                $underlyingObject = $wallEntry->content->getPolymorphicRelation();
                if ($underlyingObject === null) {
                    throw new Exception('内容获取失败.');
                }
                $underlyingObject->populateRelation('content', $wallEntry->content);

                $e['title']   = \humhub\widgets\RichText::widget(['text' => $underlyingObject->p_title, 'record' => $underlyingObject]);
                $e['message'] = \humhub\widgets\RichText::widget(['text' => $underlyingObject->message, 'record' => $underlyingObject]);

                $img = '';
                $p_guid = md5('POST:'.$underlyingObject->id);
                $file = \humhub\modules\file\models\File::findOne(['guid' => $p_guid]);
                if( $file ){
                    if ($file->getMimeBaseType() == "image"){
                        //$img = $file->getPreviewImageUrl(200, 200);
                        $img = $file->getUrl();
                    }
                }
                $e['image'] = $img;

                $e['video'] = '';
                $_video = \humhub\modules\file\models\File::findOne(['guid' => $underlyingObject->p_video]);
                if( $_video ){ $e['video'] = $_video->getUrl(); }
                $e['secs']    = $underlyingObject->p_secs;

                $e['id']         = $underlyingObject->id;
                $e['created_at'] = $underlyingObject->created_at;
                $e['updated_at'] = $underlyingObject->updated_at;

                //讲师
                //$t = json_decode($episode['teachers'], true);
                $t = json_decode($underlyingObject->p_teachers, true);
                if( isset( $t[0]) ){
                    //$o['teachers'] = $t[0];
                    $e['teachers'] = $t;
                }else{
                    //$o['teachers'] = (object)[];
                    $e['teachers'] = [];
                }

                $o['episodes'][] = $e;
            }

            //$wallOne['entry']  = $wallEntry; //table:wall_entry
            $wallOne['object'] = $o;
            $wallList[] = $wallOne;

            $generatedWallEntryIds[] = $wallEntry->id;
            $lastEntryId = $wallEntry->id;
        //}
        return [
            'output' => $wallList,
        ];
    }
}
